// 文件上传处理
function initializeFileUpload(productId) {
    // 获取文件输入元素
    const fileInput = document.getElementById('modalFileInput');
    const uploadPreview = document.createElement('div');
    uploadPreview.className = 'file-preview mt-3';
    uploadPreview.style.display = 'none';
    
    // 在文件输入控件后插入预览区域
    fileInput.parentNode.insertAdjacentElement('afterend', uploadPreview);
    
    // 监听文件选择事件
    fileInput.addEventListener('change', function(e) {
        // 清空预览区域
        uploadPreview.innerHTML = '';
        uploadPreview.style.display = 'none';
        
        // 获取选中的文件
        const files = this.files;
        
        // 检查是否选择了文件
        if (files.length === 0) {
            console.log('未选择文件');
            return;
        }
        
        // 显示预览区域
        uploadPreview.style.display = 'flex';
        uploadPreview.style.flexWrap = 'wrap';
        uploadPreview.style.gap = '10px';
        
        // 为每个文件创建预览
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            
            // 检查是否为图片
            if (!file.type.startsWith('image/')) {
                console.log(`文件 ${file.name} 不是图片，跳过预览`);
                continue;
            }
            
            // 创建预览元素
            const preview = document.createElement('div');
            preview.className = 'file-preview-item';
            preview.style.width = '100px';
            preview.style.height = '100px';
            preview.style.position = 'relative';
            preview.style.overflow = 'hidden';
            preview.style.borderRadius = '8px';
            preview.style.boxShadow = '0 2px 6px rgba(0,0,0,0.1)';
            
            // 创建图片预览
            const img = document.createElement('img');
            img.style.width = '100%';
            img.style.height = '100%';
            img.style.objectFit = 'cover';
            
            // 读取文件并设置预览图片
            const reader = new FileReader();
            reader.onload = function(e) {
                img.src = e.target.result;
            };
            reader.readAsDataURL(file);
            
            // 创建文件名显示
            const fileName = document.createElement('div');
            fileName.className = 'file-name';
            fileName.textContent = file.name.length > 20 ? file.name.substring(0, 17) + '...' : file.name;
            fileName.style.position = 'absolute';
            fileName.style.bottom = '0';
            fileName.style.left = '0';
            fileName.style.right = '0';
            fileName.style.padding = '4px';
            fileName.style.backgroundColor = 'rgba(0,0,0,0.5)';
            fileName.style.color = 'white';
            fileName.style.fontSize = '10px';
            fileName.style.textAlign = 'center';
            fileName.style.whiteSpace = 'nowrap';
            fileName.style.overflow = 'hidden';
            fileName.style.textOverflow = 'ellipsis';
            
            // 添加到预览元素
            preview.appendChild(img);
            preview.appendChild(fileName);
            
            // 添加到预览区域
            uploadPreview.appendChild(preview);
        }
        
        // 添加文件计数提示
        const fileCount = document.createElement('div');
        fileCount.className = 'file-count mt-2';
        fileCount.textContent = `已选择 ${files.length} 个文件`;
        fileCount.style.fontSize = '12px';
        fileCount.style.color = '#666';
        uploadPreview.appendChild(fileCount);
        
        console.log(`已选择 ${files.length} 个文件`);
    });

    // 使用原生fetch API处理文件上传
    document.getElementById('uploadImagesBtn').addEventListener('click', async function() {
        const files = fileInput.files;
        
        if (files.length === 0) {
            showToast('提示', '请至少选择一个文件', 'info');
            return;
        }
        
        console.log(`开始上传 ${files.length} 个文件`);
        
        // 显示上传进度
        const progressBar = document.querySelector('#uploadProgress .progress-bar');
        const uploadStatus = document.getElementById('uploadStatus');
        document.getElementById('uploadProgress').style.display = 'block';
        uploadStatus.textContent = '准备上传...';
        progressBar.style.width = '0%';
        
        // 禁用上传按钮
        this.disabled = true;
        this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 上传中...';
        
        try {
            // 创建FormData对象
            const formData = new FormData();
            
            // 添加所有文件
            for (let i = 0; i < files.length; i++) {
                formData.append('files', files[i]);
                console.log(`添加文件到FormData: ${files[i].name}, 大小: ${files[i].size} 字节`);
            }
            
            // 发送请求
            const response = await fetch(`/api/products/${productId}/files`, {
                method: 'POST',
                body: formData
            });
            
            // 检查响应状态
            if (response.ok) {
                const result = await response.json();
                console.log('上传成功:', result);
                
                // 显示成功消息
                progressBar.style.width = '100%';
                progressBar.classList.add('bg-success');
                uploadStatus.textContent = '上传成功！';
                
                // 重新加载产品详情
                setTimeout(() => {
                    // 隐藏模态框
                    const uploadModal = bootstrap.Modal.getInstance(document.getElementById('uploadModal'));
                    uploadModal.hide();
                    
                    // 重新加载产品详情
                    window.loadProductDetails();
                    
                    // 重置表单和进度条
                    document.getElementById('simpleUploadForm').reset();
                    progressBar.style.width = '0%';
                    progressBar.classList.remove('bg-success');
                    document.getElementById('uploadProgress').style.display = 'none';
                    uploadPreview.style.display = 'none';
                    uploadPreview.innerHTML = '';
                    
                    // 重置上传按钮
                    this.disabled = false;
                    this.innerHTML = '<i class="fas fa-upload"></i> 开始上传';
                }, 1500);
                
            } else {
                // 处理错误
                const errorData = await response.json();
                console.error('上传失败:', errorData);
                
                progressBar.classList.add('bg-danger');
                uploadStatus.textContent = `上传失败: ${errorData.detail || '未知错误'}`;
                
                // 重置上传按钮
                this.disabled = false;
                this.innerHTML = '<i class="fas fa-upload"></i> 重试上传';
            }
        } catch (error) {
            console.error('上传过程中发生错误:', error);
            
            progressBar.classList.add('bg-danger');
            uploadStatus.textContent = `上传出错: ${error.message || '未知错误'}`;
            
            // 重置上传按钮
            this.disabled = false;
            this.innerHTML = '<i class="fas fa-upload"></i> 重试上传';
        }
    });
}

// 显示通知
function showToast(title, message, type = 'info') {
    // 创建toast元素
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `
        <div class="toast-header">
            <i class="fas fa-${type === 'info' ? 'info-circle' : type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>
            <strong class="me-auto">${title}</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body">
            ${message}
        </div>
    `;
    
    // 添加到toast容器
    let toastContainer = document.querySelector('.toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        document.body.appendChild(toastContainer);
    }
    toastContainer.appendChild(toast);
    
    // 初始化Bootstrap toast
    const bsToast = new bootstrap.Toast(toast, {
        autohide: true,
        delay: 5000
    });
    bsToast.show();
    
    // 自动移除
    toast.addEventListener('hidden.bs.toast', () => {
        toast.remove();
    });
    
    return bsToast;
}

// 在DOMContentLoaded事件中初始化上传功能
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，准备初始化文件上传功能');
    
    // 获取productId
    const productIdElement = document.getElementById('productIdInput');
    let productId = '';
    
    if (productIdElement) {
        productId = productIdElement.value;
        console.log('从表单元素获取产品ID:', productId);
    } else {
        // 尝试从全局变量获取
        productId = window.productId;
        console.log('从全局变量获取产品ID:', productId);
    }
    
    // 检查上传按钮是否存在
    const uploadButton = document.getElementById('uploadImagesBtn');
    if (!uploadButton) {
        console.error('上传按钮元素不存在，ID: uploadImagesBtn');
    } else {
        console.log('找到上传按钮元素');
    }
    
    // 检查文件输入是否存在
    const modalFileInput = document.getElementById('modalFileInput');
    if (!modalFileInput) {
        console.error('文件输入元素不存在，ID: modalFileInput');
    } else {
        console.log('找到文件输入元素，accept:', modalFileInput.accept);
    }
    
    // 如果找到了productId，初始化上传功能
    if (productId) {
        console.log('初始化文件上传功能，产品ID:', productId);
        initializeFileUpload(productId);
    } else {
        console.error('无法找到产品ID，上传功能初始化失败');
    }
}); 